package com.dsit.hb950.file_service;

import android.content.Context;
import android.net.IpPrefix;
import android.util.Log;

import java.io.File;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.io.RandomAccessFile;
import java.net.Socket;

/**
 * Created by Administrator on 2016/10/27.
 */

public class FileUploader {
    String TAG = "FileUploader";

    public interface ProgressListener{
        void onUploading(File file,int len,int totallen);
        void onError(Exception ex);
    }

    private FileMD5Checker md5Checker;
    private UploadLogService logService;
    private boolean start=true;
    ProgressListener listener;
    private  int port;
    private String serverIp;
    Thread loadingThread;

    public FileUploader(Context context,String serverIp,int port){
        this.serverIp = serverIp;
        this.port = port;
        logService = new UploadLogService(context);
    }

    public void setListener(ProgressListener listener){
        this.listener = listener;
    }

    public void upload(final File uploadFile){
        loadingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    md5Checker = new FileMD5Checker(new File[]{uploadFile},null);
                    String souceid = logService.getBindId(uploadFile);
                    String head = "Content-Length="+ uploadFile.length()
                            + ";filename="+ uploadFile.getName()
                            + ";sourceid="+ (souceid==null? "" : souceid)
                            +";md5="+md5Checker.calculateMD5sum(uploadFile)
                            +"\r\n";

                    Log.i(TAG,"=====> file info:"+head);

                    Socket socket = new Socket(serverIp,port);
                    OutputStream outStream = socket.getOutputStream();
                    outStream.write(head.getBytes());

                    PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());
                    String response = StreamTool.readLine(inStream);
                    String[] items = response.split(";");
                    String responseid = items[0].substring(items[0].indexOf("=")+1);
                    String position = items[1].substring(items[1].indexOf("=")+1);
                    if(souceid==null){//代表原来没有上传过此文件，往数据库添加一条绑定记录
                        logService.save(responseid, uploadFile);
                    }
                    RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");
                    fileOutStream.seek(Integer.valueOf(position));
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    int length = Integer.valueOf(position);
                    while(start&&(len = fileOutStream.read(buffer)) != -1){
                        outStream.write(buffer, 0, len);
                        length += len;
                        // TODO publish length
                        if(listener!=null){
                            listener.onUploading(uploadFile,length,(int) uploadFile.length());
                        }
                    }
                    fileOutStream.close();
                    outStream.close();
                    inStream.close();
                    socket.close();
                    if(length==uploadFile.length()) logService.delete(uploadFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    if(listener!=null){
                        listener.onError(e);
                    }
                }
            }
        });loadingThread.start();
    }

}
